'use client';

import { useState } from 'react';
import { Play, Pause, Settings, RefreshCw, Plus, Wifi, WifiOff, TrendingUp } from 'lucide-react';
import StrategyModal from './StrategyModal';
import AddTokenModal from './AddTokenModal';
import RSIChartModal from './RSIChartModal';
import { useWebSocket } from './WebSocketProvider';
import { Token } from '../types/token';

export default function TokenList() {
  const [selectedToken, setSelectedToken] = useState<Token | null>(null);
  const [isStrategyModalOpen, setIsStrategyModalOpen] = useState(false);
  const [isAddTokenModalOpen, setIsAddTokenModalOpen] = useState(false);
  const [isRSIChartModalOpen, setIsRSIChartModalOpen] = useState(false);
  const { tokens, isConnected, isMonitoring, startMonitoring, stopMonitoring, lastUpdate } = useWebSocket();

  const handleRefresh = async () => {
    // WebSocket模式下不需要手动刷新，数据会自动更新
    if (isConnected && !isMonitoring) {
      startMonitoring();
    }
  };

  const toggleStrategy = async (tokenId: string, isEnabled: boolean) => {
    try {
      const response = await fetch('/api/strategies', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          tokenId,
          isEnabled: !isEnabled,
        }),
      });

      if (response.ok) {
        // WebSocket会自动更新数据，无需手动刷新
        console.log('策略状态已更新');
      }
    } catch (error) {
      console.error('切换策略状态失败:', error);
    }
  };

  const openStrategyModal = (token: Token) => {
    setSelectedToken(token);
    setIsStrategyModalOpen(true);
  };

  const openRSIChart = (token: Token) => {
    setSelectedToken(token);
    setIsRSIChartModalOpen(true);
  };

  const handleTokenAdded = () => {
    setIsAddTokenModalOpen(false);
    // WebSocket会自动获取新添加的代币数据
  };

  const getRSIColor = (rsi: number) => {
    if (rsi <= 30) return 'rsi-low';
    if (rsi >= 70) return 'rsi-high';
    return 'rsi-neutral';
  };

  const getChainColor = (chain: string) => {
    switch (chain) {
      case 'SOLANA':
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
      case 'BSC':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'BASE':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  const formatNumber = (num: number | null, decimals: number = 2) => {
    if (num === null) return '-';
    if (num >= 1e9) return (num / 1e9).toFixed(decimals) + 'B';
    if (num >= 1e6) return (num / 1e6).toFixed(decimals) + 'M';
    if (num >= 1e3) return (num / 1e3).toFixed(decimals) + 'K';
    return num.toFixed(decimals);
  };

  const formatLastUpdate = (timestamp: string | null) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return date.toLocaleTimeString('zh-CN');
  };

  return (
    <div className="space-y-4">
      {/* 头部操作栏 */}
      <div className="flex justify-between items-center">
        <div className="flex items-center space-x-4">
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
            代币列表
          </h2>
          
          {/* WebSocket连接状态 */}
          <div className="flex items-center space-x-2">
            {isConnected ? (
              <Wifi className="w-5 h-5 text-green-500" />
            ) : (
              <WifiOff className="w-5 h-5 text-red-500" />
            )}
            <span className={`text-sm ${isConnected ? 'text-green-600' : 'text-red-600'}`}>
              {isConnected ? '已连接' : '未连接'}
            </span>
          </div>

          {/* 监控状态 */}
          {isConnected && (
            <div className="flex items-center space-x-2">
              <div className={`w-2 h-2 rounded-full ${isMonitoring ? 'bg-green-500 animate-pulse' : 'bg-gray-400'}`}></div>
              <span className="text-sm text-gray-600 dark:text-gray-400">
                {isMonitoring ? '监控中' : '已停止'}
              </span>
            </div>
          )}

          {/* 最后更新时间 */}
          {lastUpdate && (
            <span className="text-xs text-gray-500 dark:text-gray-400">
              最后更新: {formatLastUpdate(lastUpdate)}
            </span>
          )}
        </div>

        <div className="flex space-x-3">
          {/* 监控控制按钮 */}
          {isConnected && (
            <button
              onClick={isMonitoring ? stopMonitoring : startMonitoring}
              className={`flex items-center space-x-2 px-4 py-2 rounded-lg font-medium ${
                isMonitoring
                  ? 'bg-red-500 hover:bg-red-600 text-white'
                  : 'bg-green-500 hover:bg-green-600 text-white'
              }`}
            >
              {isMonitoring ? (
                <>
                  <Pause className="w-4 h-4" />
                  <span>停止监控</span>
                </>
              ) : (
                <>
                  <Play className="w-4 h-4" />
                  <span>开始监控</span>
                </>
              )}
            </button>
          )}

          <button
            onClick={() => setIsAddTokenModalOpen(true)}
            className="btn-success flex items-center space-x-2"
          >
            <Plus className="w-4 h-4" />
            <span>添加代币</span>
          </button>
        </div>
      </div>

      {/* 监控状态提示 */}
      {isMonitoring && (
        <div className="bg-green-50 dark:bg-green-900 border border-green-200 dark:border-green-700 rounded-lg p-4">
          <div className="flex items-center">
            <div className="animate-pulse w-2 h-2 bg-green-500 rounded-full mr-2"></div>
            <span className="text-green-800 dark:text-green-200 text-sm font-medium">
              实时监控中 - 每2秒更新价格和RSI数据
            </span>
          </div>
        </div>
      )}

      {/* 代币表格 */}
      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="table">
            <thead>
              <tr>
                <th>代币</th>
                <th>链</th>
                <th>价格</th>
                <th>市值</th>
                <th>24h成交量</th>
                <th>24h涨跌</th>
                <th>RSI</th>
                <th>策略状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {tokens.map((token) => (
                <tr key={token.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                  <td>
                    <div>
                      <div className="font-medium">{token.symbol}</div>
                      <div className="text-sm text-gray-500 dark:text-gray-400">
                        {token.name}
                      </div>
                    </div>
                  </td>
                  <td>
                    <span className={`status-indicator ${getChainColor(token.chain)}`}>
                      {token.chain}
                    </span>
                  </td>
                  <td>
                    <div className="font-mono">
                      {token.price !== null ? 
                        `$${token.price.toFixed(6)}` : 
                        <span className="text-red-500">数据获取失败</span>
                      }
                    </div>
                  </td>
                  <td>
                    <div className="font-mono">
                      {token.marketCap !== null ? 
                        `$${formatNumber(token.marketCap)}` : 
                        <span className="text-gray-400">-</span>
                      }
                    </div>
                  </td>
                  <td>
                    <div className="font-mono">
                      {token.volume24h !== null && token.volume24h !== undefined ? 
                        `$${formatNumber(token.volume24h)}` : 
                        <span className="text-gray-400">-</span>
                      }
                    </div>
                  </td>
                  <td>
                    <div className={`font-mono ${
                      token.priceChange24h !== null && token.priceChange24h !== undefined
                        ? token.priceChange24h >= 0 ? 'text-green-600' : 'text-red-600'
                        : 'text-gray-400'
                    }`}>
                      {token.priceChange24h !== null && token.priceChange24h !== undefined ? (
                        <>
                          {token.priceChange24h >= 0 ? '+' : ''}
                          {token.priceChange24h.toFixed(2)}%
                        </>
                      ) : (
                        <span>-</span>
                      )}
                    </div>
                  </td>
                  <td>
                    <div 
                      className={`font-mono font-bold cursor-pointer hover:bg-gray-700 px-2 py-1 rounded transition-colors flex items-center gap-1 ${token.rsi !== null ? getRSIColor(token.rsi) : 'text-gray-400'}`}
                      onClick={() => openRSIChart(token)}
                      title="点击查看RSI图表"
                    >
                      {token.rsi !== null ? token.rsi.toFixed(1) : '-'}
                      <TrendingUp size={14} className="opacity-60" />
                    </div>
                  </td>
                  <td>
                    {token.strategy ? (
                      <span className={`status-indicator ${
                        token.strategy.isEnabled ? 'status-active' : 'status-inactive'
                      }`}>
                        {token.strategy.isEnabled ? '运行中' : '已停止'}
                      </span>
                    ) : (
                      <span className="status-indicator status-inactive">
                        未配置
                      </span>
                    )}
                  </td>
                  <td>
                    <div className="flex space-x-2">
                      {token.strategy && (
                        <button
                          onClick={() => toggleStrategy(token.id, token.strategy!.isEnabled)}
                          className={`p-2 rounded-lg ${
                            token.strategy.isEnabled
                              ? 'text-red-600 hover:bg-red-50 dark:hover:bg-red-900'
                              : 'text-green-600 hover:bg-green-50 dark:hover:bg-green-900'
                          }`}
                          title={token.strategy.isEnabled ? '停止交易' : '开始交易'}
                        >
                          {token.strategy.isEnabled ? (
                            <Pause className="w-4 h-4" />
                          ) : (
                            <Play className="w-4 h-4" />
                          )}
                        </button>
                      )}
                      <button
                        onClick={() => openStrategyModal(token)}
                        className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded-lg"
                        title="策略设置"
                      >
                        <Settings className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {tokens.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500 dark:text-gray-400">
              暂无代币数据，请先添加代币
            </p>
          </div>
        )}
      </div>

      {/* 策略配置模态框 */}
      {selectedToken && (
        <StrategyModal
          isOpen={isStrategyModalOpen}
          onClose={() => setIsStrategyModalOpen(false)}
          token={selectedToken}
          onSaved={handleRefresh}
        />
      )}

      {/* 添加代币模态框 */}
      <AddTokenModal
        isOpen={isAddTokenModalOpen}
        onClose={() => setIsAddTokenModalOpen(false)}
        onTokenAdded={handleTokenAdded}
      />

      {/* RSI图表模态框 */}
      <RSIChartModal
        isOpen={isRSIChartModalOpen}
        onClose={() => setIsRSIChartModalOpen(false)}
        token={selectedToken}
      />
    </div>
  );
}
